package com.zbkc.main;

import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.zbkc.bean.FileBoxBean;
import com.zbkc.constant.Constant;
import com.zbkc.interfaces.SCInterface;
import com.zbkc.main.base.BaseTitleActivity;
import com.zbkc.util.AlertUtils;
import com.zbkc.util.BASE64Util;
import com.zbkc.util.LogUtil;
import com.zbkc.util.PreferenceUtils;
import com.zbkc.util.StarCloudUtil;
import com.zbkc.util.ThreadPoolFactory;
import com.zbkc.util.ToastUtil;

public class FileCupboardActivity extends BaseTitleActivity {

	private Button btnValidation;
	private CheckBox checkBox;
	private EditText etPassword;
	private List<FileBoxBean> boxBeans;

	private ListView listView;
	private LinearLayout llPassword;
	private MyAdapter myAdapter;

	private String downResult;
	private String message = null;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				myAdapter = new MyAdapter(FileCupboardActivity.this, 0,
						boxBeans);
				listView.setAdapter(myAdapter);
				llPassword.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				AlertUtils.dismissLoadingDialog();
				break;

			case 2:
				LogUtil.e("下载结果:" + downResult);
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_cupboard);
		bindView();
	}

	private void bindView() {
		setTitle("文件保险箱");
		setBtn1Visiable(false);
		setBtn2Visiable(false);

		etPassword = ((EditText) findViewById(R.id.et_pwd));
		etPassword.addTextChangedListener(new addTextChange());
		btnValidation = ((Button) findViewById(R.id.btn_validation));
		btnValidation.setOnClickListener(this);
		btnValidation.setVisibility(View.INVISIBLE);

		checkBox = ((CheckBox) findViewById(R.id.checkbox));
		checkBox.setOnCheckedChangeListener(new CheckChangeLisenter());

		llPassword = ((LinearLayout) findViewById(R.id.ll_password));

		listView = ((ListView) findViewById(R.id.listview));
		listView.setOnItemClickListener(new ItemClickLisenter());

		boolean isSave = PreferenceUtils.getBoolean(Constant.IS_SAVE_PASSWORD,
				false);
		String password = PreferenceUtils.getString(Constant.FILE_PASSWORD);
		if (isSave) {
			// 已经保存了
			checkBox.setChecked(true);
			listView.setVisibility(View.VISIBLE);
			llPassword.setVisibility(View.GONE);
			message = "正在获取数据,请稍后...";
			getData(password);
		} else {
			// 没有保存密码
			checkBox.setChecked(false);
			listView.setVisibility(View.GONE);
			llPassword.setVisibility(View.VISIBLE);
			message = "保险箱密码验证中,请稍后...";
		}
	}

	private void getData(String password) {
		AlertUtils.showLoadingDialog(this, message, true);
		final String str = StarCloudUtil.MD5(password);
		final String str1 = str.substring(0, 5) + "asdfrtyuiabcdbgfre34";
		final String str2 = str.substring(5);
		ThreadPoolFactory.getInstance().execute(new Runnable() {
			public void run() {
				boxBeans = SCInterface.getFileBox(
						BASE64Util.encode(str1.getBytes()),
						BASE64Util.encode(str2.getBytes()));
				handler.sendEmptyMessage(1);
			}
		});
	}

	public void onClick(View paramView) {
		switch (paramView.getId()) {
		case R.id.btn_validation:
			String password = etPassword.getText().toString().trim();
			if (TextUtils.isEmpty(password)) {
				ToastUtil.showToast(FileCupboardActivity.this, "文件保险箱密码不能为空");
				return;
			}

			boolean isSave = checkBox.isChecked();
			if (isSave) {
				PreferenceUtils.putString(Constant.FILE_PASSWORD, password);
			}
			getData(password);
			break;
		}

	}

	class CheckChangeLisenter implements OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			PreferenceUtils.putBoolean(Constant.IS_SAVE_PASSWORD, isChecked);

		}

	}

	class ItemClickLisenter implements AdapterView.OnItemClickListener {

		public void onItemClick(AdapterView<?> paramAdapterView,
				View paramView, final int position, long paramLong) {

			ThreadPoolFactory.getInstance().execute(new Runnable() {

				@Override
				public void run() {
					FileBoxBean boxBean = boxBeans.get(position);
					LogUtil.e("filename" + boxBean.getFilename());
					LogUtil.e("mark1" + boxBean.getMaker1());
					LogUtil.e("mark2" + boxBean.getMaker2());
					downResult = SCInterface.downFile(boxBean.getMaker1(),
							boxBean.getMaker2(), boxBean.getFilename());
					handler.sendEmptyMessage(2);
				}
			});

			// LogUtil.e("文件夹名:" + Config.FILE_LOCATION);
			// fileurl = (Config.FILE_LOCATION + ((ShareFileBean) fileBeanList
			// .get(paramInt)).getFilename());
			// if (new File(FileCupboardActivity.this.fileurl).exists()) {
			// handler.sendEmptyMessage(2);
			// return;
			// }
			// AlertUtils.showLoadingDialog(FileCupboardActivity.this,
			// "正在打开文件,请稍后...", true);
			// ThreadPoolFactory.getInstance().execute(new Runnable() {
			// public void run() {
			// // result = SCInterface
			// // .downFile(
			// // ((ShareFileBean) FileCupboardActivity.this.fileBeanList
			// // .get(paramInt)).getMake1(),
			// // ((ShareFileBean) FileCupboardActivity.this.fileBeanList
			// // .get(paramInt)).getMake2(),
			// // ((ShareFileBean) FileCupboardActivity.this.fileBeanList
			// // .get(paramInt)).getFilename());
			// // handler.sendEmptyMessage(2);
			// }
			// });
		}
	}

	class MyAdapter extends ArrayAdapter<FileBoxBean> {

		public MyAdapter(Context context, int textViewResourceId,
				List<FileBoxBean> objects) {
			super(context, textViewResourceId, objects);
		}

		public View getView(int position, View paramView,
				ViewGroup paramViewGroup) {
			ViewHolder viewHolder;
			if (paramView == null) {
				viewHolder = new ViewHolder();
				paramView = View.inflate(getContext(),
						R.layout.listview_beifen_item, null);
				viewHolder.tvtitle = ((TextView) paramView
						.findViewById(R.id.tv_title));
				paramView.setTag(viewHolder);
			} else {
				viewHolder = ((ViewHolder) paramView.getTag());
			}
			viewHolder.tvtitle.setText(getItem(position).getFilename());
			return paramView;
		}

		class ViewHolder {
			TextView tvtitle;
		}
	}

	class addTextChange implements TextWatcher {
		addTextChange() {
		}

		public void afterTextChanged(Editable paramEditable) {
		}

		public void beforeTextChanged(CharSequence paramCharSequence,
				int paramInt1, int paramInt2, int paramInt3) {
		}

		public void onTextChanged(CharSequence paramCharSequence,
				int paramInt1, int paramInt2, int paramInt3) {
			if (TextUtils.isEmpty(paramCharSequence.toString())) {
				btnValidation.setVisibility(View.INVISIBLE);
			} else {
				btnValidation.setVisibility(View.VISIBLE);
			}
		}
	}

}
